<template>
  <div class="container">
    <!--头部筛选 start-->
    <div class="flex-row justify-between p_b10">
      <div>
        <el-input size="small" v-model="params.filter" placeholder="搜索关键词..." class="m_r10 width200"></el-input>
        <el-button size="small" type="primary" icon="el-icon-search" @click="onPageChange(1)"></el-button>
        <el-button size="small" type="primary" @click="onPageChange(1)">刷新</el-button>
      </div>
      <div>
        <!--<el-button size="small" type="primary" @click="toggleEditorModal(true)">新增商品</el-button>-->
      </div>
    </div>
    <!--头部筛选 end-->

    <!--列表数据 start-->
    <el-table :data="tableData" border size="mini">
      <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
      <el-table-column prop="carId" :min-width="200" label="预约课程">
        <template v-slot="{row}">
          {{ coursesMap[row.courseId] }}
        </template>
      </el-table-column>
      <el-table-column
          prop="userName" align="center"
          :min-width="100" label="预约学生"
          v-if="role!=='student'"></el-table-column>
      <el-table-column
          prop="thName" align="center"
          v-if="role!=='teacher'"
          :min-width="100" label="预约老师"></el-table-column>
      <el-table-column prop="time" :min-width="400" label="预约时间">
        <template v-slot="{row}">
          {{ format(row.stime) }}
          <span class="p_x5">~</span>
          {{ format(row.etime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" :min-width="120" align="center" label="状态">
        <template v-slot="{row}">
          <el-tag type="info" v-if="row.status===0">待通过</el-tag>
          <el-tag type="success" v-else-if="row.status===1">成功预约</el-tag>
          <el-tag type="danger" v-else-if="row.status===2">拒绝的预约</el-tag>
          <el-tag type="info" v-else-if="row.status===3">完成预约</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" :min-width="180" align="center" label="提交时间">
        <template v-slot="{row}">
          {{ format(row.startTime) }}
        </template>
      </el-table-column>

      <el-table-column
          label="操作" :width="120"
          v-if="role!=='student'"
          align="center" fixed="right">
        <template #default="{row}">
          <el-button
              :disabled="row.status>=3"
              plain round
              type="success"
              @click="toggleCommentModal(true, row)" size="mini">
            改变状态
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <!--列表数据 end-->


    <!--分页组件 start-->
    <div class="pagination">
      <el-pagination
          background layout="total, prev, pager, next"
          :current-page="pageMeta.current_page"
          :page-size="pageMeta.limit" :total="pageMeta.total"
          @current-change="onPageChange"></el-pagination>
    </div>
    <!--分页组件 end-->


    <!--设置预约状态弹框 start-->
    <el-dialog
        v-model="commentFormData.show"
        title="设置预约状态"
        width="50%">
      <el-form label-position="top" label-width="120px">
        <el-form-item label="">
          <el-radio-group v-model="commentFormData.status">
            <el-radio :label="1">预约成功</el-radio>
            <el-radio :label="2">拒绝预约</el-radio>
            <el-radio :label="3">完成预约</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="toggleCommentModal(false)">取消</el-button>
          <el-button size="small" type="primary" @click="onComment()">提交保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!--设置预约状态弹框 end-->
  </div>


</template>

<script>
import {computed, defineComponent, reactive, ref, toRaw} from "vue"
import {usePageMeta} from "../../hooks/usePageTableData";
import {deepClone} from "../../utils/helpers";
import Toast from "../../utils/Toast";
import Orders from "../../api/modules/Orders";
import {useStore} from "vuex";
import dayjs from "dayjs";
import {useCourses} from "../../hooks/useCourses";
import {RoleTypes} from "../../hooks/user/useUserLogin";

export default defineComponent({
  name: "Orders",
  data() {
    return {
      rules: {
        name: [
          {required: true, message: "请填写名称"}
        ],
        price: [
          {required: true, message: "请填写价格"},
          {type: 'number', min: 0, max: 99999, transform: v => Number(v) || '', message: "价格范围在0~99999之间"},
        ]
      },
    }
  },
  methods: {
    format(time, layout = 'YYYY-MM-DD HH:mm:ss') {
      return dayjs(time).format(layout)
    }
  },
  setup() {
    const store = useStore();
    const formRefName = ref(null);
    const pageHandle = usePageMeta(); // 分页相关数据
    const courseHandle = useCourses(); // 所有课程获取
    const role = computed(() => store.state.user.role)
    const params = reactive({ // 筛选条件
      filter: "",
    });
    const tableData = ref([]); // 接口返回的数据列表

    onPageChange(1); // 初始化时直接请求一次分类列表


    const commentFormData = reactive({ // 设置状态表单数据
      show: false, // 是否打开弹框
      row: {}, // 设置的订单数据行
      status: 0 // 状态 0待通过，1成功预约，2被拒绝的预约，3完成的预约
    });

    /**
     * 打开、关闭状态设置框
     * @param show {boolean} true:打开 false 关闭
     * @param row
     */
    function toggleCommentModal(show, row = {}) {
      commentFormData.show = show;
      commentFormData.row = row;
      commentFormData.status = row.status || 0;

    }


    // 保存预约状态
    async function onComment() {
      if (commentFormData.status === commentFormData.row.status) {
        return;
      }
      try {
        const res = await Orders.setStatus({
          status: commentFormData.status,
          id: commentFormData.row.id,
        });
        Toast.success(res.message || '保存成功');
        toggleCommentModal(false)
        onPageChange(); // 保存预约状态成功(刷新列表数据)
      } catch (e) {
        console.log(e)
        Toast.error(e.message || '保存失败')
      }
    }

    /**
     * 获取订单列表数据
     * @param page page===undefined时表示刷新当前页面
     * @returns {Promise<void>}
     */
    async function onPageChange(page) {
      const pageMeta = deepClone(toRaw(pageHandle.pageMeta.value));
      if (page) {
        pageMeta.index = page;
      }
      try {
        const _params = {
          ...pageMeta, // 分页数据（当前页数，每页请求数量等）
          ...params, // 筛选参数（搜索条件等）
          thId: store.state.user.userInfo.id,
        };
        if (role.value === RoleTypes.student) { // 当前登录是学生账户
          _params.userId = store.state.user.userInfo.id;
        } else if (role.value === RoleTypes.student) { // 当前登录是教师账户
          _params.thSno = store.state.user.userInfo.id;
        }

        const {data} = await Orders.lists(_params);
        tableData.value = (data.data || []).map(item => {
          if (item.car) {
            try {
              // 对每一项目中存在的车辆图片json字符串 转换为json数组
              item.car.images = JSON.parse(item.car.images);
            } catch (e) {

            }
          }
          return item;
        });
        // 请求到数据，更新公共的分页数据页码数
        pageHandle.updatePageMeta(pageMeta.index, data.count);

      } catch (e) {
        console.log(e);
      }
    }


    return {
      ...pageHandle,
      ...courseHandle,
      commentFormData,
      toggleCommentModal,
      role,
      params,
      onComment,
      formRefName,
      tableData,
      onPageChange,
    }
  },
})
</script>

<style lang="scss" scoped>
.car-image {
  width: 60px;
  height: 40px;
}

.user-cover {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
</style>
